# -*- coding: utf-8 -*-
"""
@File    : xizang_lasashi_shtml_policy
@Author  : caojy
@Time    : 24/12/03 10:27
"""
import datetime
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XizanglasashiShtmlPolicy(BaseTaxPolicySpider):
    name = 'xizang_lasashi_shtml_policy'

    province = '西藏自治区'
    city = '拉萨市'
    county = ''
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['拉萨市当雄县人民政府', '当雄县', 'https://www.dxx.gov.cn/dxxrmzf/gfxwj/zfxxgk_list.shtml'],
            ['拉萨市尼木县人民政府', '尼木县', 'https://www.nmx.gov.cn/nmx/gfxwj/zfxxgk_list.shtml'],
            ['拉萨市曲水县人民政府', '曲水县', 'https://www.qushuixian.gov.cn/qsx/gfxwj/zfxxgk_list.shtml'],
            ['拉萨市城关区人民政府', '城关区', 'https://www.cgq.gov.cn/cgqrmzf/gfxwj/zfxxgk_list.shtml'],
            ['拉萨市达孜区人民政府', '达孜区', 'https://www.dzq.gov.cn/dzqzf/gfxwj/zfxxgk_list.shtml'],
            ['拉萨市林周县人民政府', '林周县', 'https://www.linzhouxian.gov.cn/lzxrmzf/gfxwj/zfxxgk_list.shtml'],
            ['拉萨市堆龙德庆区人民政府', '堆龙德庆区', 'https://www.dldqq.gov.cn/dldqqrmzf/gfxwj/zfxxgk_list.shtml'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='table-main' or @class='table-responsive' or @class='govnewslista2353']//td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=2] |"
                "//div[@class='table-main' or @class='zfxxgk_right']//dd//a[contains(@href, 'htm') or @title]/ancestor::dd[string-length(string(.))>=2] |"
                "//table[@id='gk_list_table' or @class='table']/tr/td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=2] |"
                "//td[@class='info']//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=2] |"
                "//ul[@class='zfxxgk-nr-cnet']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=2]"
        ):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or response.xpath("//script").re_first(r"""createPageHTML\('paging',(\d+),""") or 0
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace(".shtml", f"_{page_num}.shtml")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xizang_lasashi_shtml_policy".split())
